<script setup>

</script>

<template>
  <div>
    <el-container>
      <!--       aside -->
      <!--      100vh为整个窗口高度-->
      <el-aside style="width:200px; min-height: 100vh;background-color: #15293b">
        <div style="height: 60px; color: aliceblue; display: flex; align-items: center;justify-content: center" >
          <img :src="require('@/assets/library.jpg')" style="height: 80%;" @click="returnTo">
        </div>
        <!--        侧边导航栏-->

        <el-menu style="border: none" :default-active="$route.path" router background-color="#15293b" text-color="rgba(255,255,255,0.65)" active-text-color="#FFF"  @select="handleSelect">
          <el-menu-item index="/personbook">
            <template slot="title">
              <i class="el-icon-s-management"></i>
              <span>借阅书籍</span>
            </template>
          </el-menu-item>
          <el-menu-item @click="toPerson()">
            <template slot="title">
              <i class="el-icon-user"></i>
              <span>用户信息</span>
            </template>
          </el-menu-item>
        </el-menu>

      </el-aside>


      <el-container>
        <!-- header -->
        <el-header style="display: flex; align-items: center; justify-content: space-between; height: 60px; background-color: #2c3e50; color: white;">
          <div style="text-align: center; width: 100%;">个人中心</div>
          <el-button @click="back()" size="mini" type="primary">返回</el-button>
        </el-header>

        <!-- main -->
        <el-main style="margin: 0 auto; width: 90%;">
          <template>
            <div>
              <el-container>
                <el-main style="margin: 0 auto; width: 90%;">
                  <el-dialog title="确认归还" :visible.sync="showDialog">
                    <img :src="QRsrc" alt="QRcode" style="width: 500px">
                    <span slot="footer" class="dialog-footer">

                    <el-button @click="showDialog = false">取消</el-button>
                    <el-button type="primary" @click="confirmReturn">确定归还</el-button>
                      </span>
                  </el-dialog>

                  <el-table :data="bookData" style="width: 100%">
                    <el-table-column prop="recordid" label="ID" width="50" align="center"></el-table-column>
                    <el-table-column prop="bookname" label="书籍" width="200" align="center"></el-table-column>
                    <el-table-column prop="author" label="作者" width="150" align="center"></el-table-column>
                    <el-table-column prop="category" label="类型" width="150" align="center"></el-table-column>
                    <el-table-column prop="press" label="出版社" width="200" align="center"></el-table-column>
                    <el-table-column label="到期日期" width="250" align="center">
                      <template slot-scope="scope">
                        {{ formatDate(scope.row.expire_time) }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="surplus" label="书本剩余" width="150" align="center"></el-table-column>
                    <el-table-column label="操作" width="100" align="center">
                      <template slot-scope="scope">
                        <el-button size="primary" @click="handleReturn(scope.row.recordid)">归还</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-main>
              </el-container>
            </div>
          </template>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>


<script>
import axios from "axios";
import Cookies from "js-cookie";

export default {
  name: "PersonBookView",
  data() {
    return {
      userid: null,
      bookData: [],
      showDialog: false,
      currentId: '',
      QRsrc: '',
      bookid: 1,
    };
  },
  methods: {
    formatDate(dateStr) {
      const date = new Date(dateStr);
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        inputText: 'https://www.baidu.com/?tn=15007414_15_dg&ie=utf-8',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    handleReturn(id) {
      this.currentId = id;
      console.log(id)
      let foundBook = this.bookData.find(book => book.recordid === id);
      this.bookid = foundBook.bookid
      this.showDialog = true;
      axios.get(`http://127.0.0.1:5000/v1/books/generate_qrcode/${this.bookid}`,{
        headers: { 'token': Cookies.get('token')}
      }).then(response => {
        if (response.data.status === 200){
          this.QRsrc = response.data.data;
        }else{
          this.$message.error('获取二维码失败');
        }
      }).catch(error => {
            this.$message({
              type: 'error',
              message: '获取失败'
            })
            console.error("Error getQRCode:", error.response);
      });
    },
    confirmReturn() {
      console.log('归还书籍:', this.currentId);
      // 进行实际的归还书籍操作
      axios.post(`http://127.0.0.1:5000/v1/books/return`, {
        recordid: this.currentId,  // 传递参数 this.currentId
        headers: { 'token': Cookies.get('token') }
      }).then(response => {
        console.log(response.data);  // 可以在控制台打印返回的数据
        this.$message.success('归还成功')
        this.update();
        // 可以根据后端返回的数据执行相应的操作
      }).catch(error => {
        console.error('Error:', error);
        let message = '归还书籍失败，请稍后再试';
        if (error.response && error.response.data && error.response.data.message) {
          message = error.response.data.message;
        }
        this.$message({
          message: message,
          type: 'error'
        });
      });
      this.showDialog = false;  // 关闭对话框
    },
    update(){
      axios.get(`http://127.0.0.1:5000/v1/users/getBorrowedBooks/${this.userid}`, {
        headers: { 'token': Cookies.get('token') }
      }).then(response => {
        if (response && response.data && response.data.data) {
          this.bookData = response.data.data;
        }
      }).catch(error => {
        console.error("Error loading data:", error);
      });
    },
    back() {
      const message = this.$route.params.message;  // 获取路由参数
    if (message === "this is admin") {
      this.$router.push({ name: 'home' });
  } else {
      // 如果 message 不是 "this is admin"，执行以下代码
      this.$router.push({ name: 'userborrowview' });
  }
    },
    toPerson(){
      const message = this.$route.params.message;
      this.$router.push({ name: 'person',params: { message } });
    },
    returnTo(){
      this.$router.push({name: 'userborrowview'})
    },
  },
  mounted() {
    console.log(this.$refs.qrcodeCanvas);
    this.userid = Cookies.get('userid');
    if (this.userid) {
      axios.get(`http://127.0.0.1:5000/v1/users/getBorrowedBooks/${this.userid}`, {
        headers: { 'token': Cookies.get('token') }
      }).then(response => {
        console.log(response)
        if (response && response.data && response.data.data) {
          this.bookData = response.data.data;
        }
      }).catch(error => {
        console.error("Error loading data:", error);
      });

    }
  },
};
</script>

<style lang="less" scoped>
</style>